import AuthComponent from '@/components/Authorized/AuthComponent';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, Menu, message, Modal, Select, DatePicker, Input } from 'antd';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';

import ProTable from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import UpdateForm from './components/UpdateForm';
import { getVipRoom, addVipRoom, updateVipRoom, removeVipRoom, queryCityInfo } from './service';

import moment from 'moment';
import styles from './index.less';

const { confirm } = Modal;
const { Option } = Select;

let hiddenData = null;
const OversaleInfoTable = props => {
  // const { data: selectData } = useRequest(queryCityInfo);
  const [createModalVisible, handleCreateModalVisible] = useState(false);
  const [updateModalVisible, handleUpdateModalVisible] = useState(false);
  const [updateData, saveUpdateData] = useState({});

  const actionRef = useRef();
  const ref = useRef();
  const searchRef = useRef();

  const reloadTable = useCallback(function reloadData() {
    if (searchRef.current) {
      searchRef.current.click();
    }
  }, []);

  const [height, controlH] = useState(320);
 

  const columns = [
    {
      title: '机场名称',
      dataIndex: 'areaName',
      hideInSearch: true,
    },
    {
      title: '贵宾室名称',
      dataIndex: 'roomName',
      hideInSearch: true,
    },
    {
      title: '扫码枪编号',
      dataIndex: 'barcodeGun',
      hideInSearch: true,
    },
  ];

  const [selectedRowKeys, handleSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, handleSelectedRows] = useState([]); // 勾选列

  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    handleSelectedRowKeys(selectedRowKeys);
    handleSelectedRows(selectedRows);
  };

  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  // 新增保存
  const handleAdd = async fields => {
    const hide = message.loading('正在添加');
    try {
      let res = await addVipRoom({ ...fields });
      if (res.code === '0') {
        hide();
        message.success('添加成功');
        return true;
      } else {
        hide();
      }
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      return false;
    }
  };
  // 编辑保存
  const handleUpdate = async fields => {
    const hide = message.loading('正在更新');
    try {
      let res = await updateVipRoom(fields);
      if (res.code === '0') {
        hide();
        message.success('更新成功');
        return true;
      } else {
        hide();
      }
    } catch (error) {
      hide();
      message.error('更新失败请重试！');
      return false;
    }
  };
  //删除
  const handleRemove = async selectedRows => {
    try {
      await removeVipRoom({
        ids: selectedRows.map(row => row.id).toString(),
      });
      message.success('删除成功，即将刷新');
      return true;
    } catch (error) {
      message.error('删除失败，请重试');
      return false;
    }
  };
  return (
    <div>
      <ProTable
        headerTitle={
          <span style={{ paddingRight: 10, fontWeight: 'bold', color: '#000' }}>贵宾室列表</span>
        }
        className={`${styles.vipMaintainTable} `}
        actionRef={actionRef}
        formRef={ref}
        options={{ density: false, fullScreen: true, reload:false, setting: true }}
        rowKey="id"
        size="small"
        scroll={{ x: 1200, y: height }}
        rowSelection={rowSelection}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode="vipRoom.maintain.add">
            <Button icon="plus" type="primary" onClick={() => handleCreateModalVisible(true)}>
              新建
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="vipRoom.maintain.edit">
            <Button
              icon="edit"
              onClick={() => {
                if (selectedRowKeys.length > 1) {
                  message.error('只能选择一条进行编辑');
                } else if (selectedRowKeys.length === 0) {
                  message.error('请选择编辑的条目');
                } else {
                  saveUpdateData(selectedRows[0]);
                  handleUpdateModalVisible(true);
                }
              }}
            >
              编辑
            </Button>
          </AuthComponent>,
          <AuthComponent authCode="vipRoom.maintain.delete">
            <Button
              icon="delete"
              selectedKeys={[]}
              onClick={() => {
                if (selectedRowKeys.length === 0) {
                  message.error('请选择删除的条目');
                } else {
                  confirm({
                    title: '提示',
                    content: '确认操作后该贵宾室数据将被删除，无法使用，你还要继续吗？',
                    cancelText: '取消',
                    okText: '确认',
                    onOk: async () => {
                      let res = await handleRemove(selectedRows);
                      if (res) {
                        actionRef.current.reload();
                        handleSelectedRows([]);
                        handleSelectedRowKeys([]);
                      }
                    },
                  });
                }
              }}
            >
              删除
            </Button>
          </AuthComponent>
        ]}
        search={false}
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`,
        }}
        request={params => {
          return getVipRoom({...params});
        }}
        
        tableAlertRender={() => {
          return false;
        }}
        columns={columns}
      />
      <CreateForm
        onSubmit={async value => {
          let params = value;
          const success = await handleAdd(params);
          if (success) {
            handleCreateModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleCreateModalVisible(false)}
        createModalVisible={createModalVisible}
      />

      <UpdateForm
        onSubmit={async value => {
          let params = value;
          const success = await handleUpdate(params);
          if (success) {
            handleUpdateModalVisible(false);
            handleSelectedRows([]);
            handleSelectedRowKeys([]);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => handleUpdateModalVisible(false)}
        updateModalVisible={updateModalVisible}
        updateData={updateData}
      />
    </div>
  );
};

export default Form.create()(OversaleInfoTable);
